package net.osc.addrpsr;

import java.util.Arrays;

import org.parboiled.Action;
import org.parboiled.Context;
import org.parboiled.Rule;

import net.osc.addrpsr.models.Address;

/**
 * User: ken
 * Date: 13-7-31
 */
public class XiamenAddressParser extends AddressParser {

    public String[] roads;

    public String[] buildings;

    public XiamenAddressParser(String[] roads, String[] buildings) {
        this.roads = roads;
        this.buildings = buildings;
    }

    @Override
    public Rule DistrictName() {
        return Sequence(
            super.DistrictName(),
            new Action<Object>() {
                @Override
                public boolean run(Context<Object> context) {
                    Object o = context.getValueStack().peek();
                    if (o == null || !(o instanceof Address)) { return true; }

                    Address addr = (Address) o;
                    String match = context.getMatch();

                    String[] districts = Regions.districtsOf("厦门");
                    return !"厦门".equals(addr.city) || Arrays.asList(districts).contains(match);
                }
            });
    }

    @Override
    public Rule Road() {
        return FirstOf(
            XiamenRoad(),
            super.Road()
        );
    }

    public Rule XiamenRoad() {
        return Sequence(
            FirstOf(roads), push(popAsAddress().road(match())),
            Optional(RoadNumber())
        );
    }

    @Override
    public Rule Building() {
        return FirstOf(
            XiamenBuilding(),
            super.Building()
        );
    }

    public Rule XiamenBuilding() {

        return Sequence(
            FirstOf(buildings), push(popAsAddress().building(match())),
            Optional(BuildingNumber())
        );
    }

}
